﻿using System;
using System . Collections . Generic;
using System . Collections . ObjectModel;
using System . Linq;
using System . Text;
using System . IO;
using System . Xml . Linq;

namespace WenceyWang . RichMan4L . Maps
{
	public class Map : GameObject
	{
		public static Map Currnet { get; set; }

		public string Name { get; set; }

		public MapSize Size { get; set; }

		public List<MapObject> Objects { get; private set; }

		public Road GetRoad ( long id )
		{
			return ( Objects . Single ( ( road ) => ( ( road as Road )?.Id == id ) ) ) as Road;
		}

		public Area GetArea ( long id )
		{
			return ( Objects . Single ( ( area ) => ( ( area as Area )?.Id == id ) ) ) as Area;
		}

		Map ( XDocument document ) : this ( )
		{

			var ele = document . Root;
			Name = ele . Attribute ( nameof( Name ) ) . Value;
			Size = new MapSize ( Convert . ToInt32 ( ele . Attribute ( "SizeX" ) . Value ) , Convert . ToInt32 ( ele . Attribute ( "SizeY" ) . Value ) );
			foreach ( var item in ele . Element ( "MapObjects" ) . Elements ( ) )
			{
				Objects . Add ( Activator . CreateInstance ( Type . GetType ( "WenceyWang.RichMan4L.Maps." + item . Name ) , new object [ ] { item } ) as MapObject );
			}
		}

		public Map ( Stream stream ) : this ( XDocument . Parse ( new StreamReader ( stream ) . ReadToEnd ( ) ) ) { }

		public Map ( ) : base ( )
		{
			Currnet = this;
			Objects = new List<MapObject> ( );
			//todo
		}

		public Map ( string flieName ) : this ( ResourceHelper . LoadXmlDocument ( @"Maps.Resources." + flieName ) ) { }


		public override void EndToday ( )
		{
			throw new NotImplementedException ( );
		}

		public override void StartDay ( Calendars . GameDate nextDate )
		{
			throw new NotImplementedException ( );
		}

		/// <summary>
		/// 销毁这个Map
		/// </summary>
		/// <param name="disposing"></param>
		protected override void Dispose ( bool disposing )
		{
			if ( disposedValue )
			{
				if ( disposing )
				{
					Currnet = null;
					foreach ( var item in Objects )
					{
						item . Dispose ( );
					}
					Objects . Clear ( );
				}
			}
			base . Dispose ( disposing );
		}

		public void RegisterView ( )
		{

		}

	}

}